package ru.housewife.service.dishes;

import org.hibernate.Session;
import ru.common.hibernate.HibernateAction;
import ru.housewife.form.EatingMenuDishRecipeForm;
import ru.housewife.form.EatingMenuForm;
import ru.housewife.model.EatingMenu;
import ru.housewife.model.EatingMenuDishRecipe;

import java.util.Iterator;

/**
 * modifies eating menu - removes dish from it (CookingDishMenu IS NOT REMOVED FROM DB)
 *
 * @author Alexander Troshanin
 */
public class RemoveDishFromEatingMenu implements HibernateAction<Boolean> {

    private EatingMenuForm eatingMenuForm;

    private EatingMenuDishRecipeForm eatingMenuRecipeForm; // to be removed from eating menu

    public RemoveDishFromEatingMenu(EatingMenuForm eatingMenuForm, EatingMenuDishRecipeForm eatingMenuRecipeForm) {
        this.eatingMenuForm = eatingMenuForm;
        this.eatingMenuRecipeForm = eatingMenuRecipeForm;
    }

    @Override
    public Boolean execute(Session session) {

        EatingMenu eatingMenu = (EatingMenu) session.get(EatingMenu.class, eatingMenuForm.getId());
        if (eatingMenu == null) {
            return false;
        }

        EatingMenuDishRecipe eatingMenuRecipe = (EatingMenuDishRecipe) session.get(EatingMenuDishRecipe.class, eatingMenuRecipeForm.getId());
        if (eatingMenuRecipe == null) {
            return false;
        }

        for (Iterator<EatingMenuDishRecipe> iter = eatingMenu.getEatingMenuRecipes().iterator(); iter.hasNext();) {
            EatingMenuDishRecipe recipe = iter.next();
            if (recipe.getId() == eatingMenuRecipeForm.getId()) {
                iter.remove();
                session.save(eatingMenu);
                session.delete(eatingMenuRecipe);
                eatingMenuForm.removeEatingMenuRecipe(eatingMenuRecipe.getId());
                return true;
            }
        }
        return false;
    }
    
}
